package com.myTest.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.myTest.io.Resources;
import com.myTest.pojo.Configuration;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XMLConfigBuilder {
    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    /**
     *该方法就是使用dom4j对配置文件进行解析，封装到Configuration中
     */
    public Configuration paresConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(inputStream);
        //得到xml配置文件中的configuration对象
        Element rootElement = document.getRootElement();
        //查找property对象集，//为任意位置
        List<Element> list = rootElement.selectNodes("//property");
        Properties properties = new Properties();
        for (Element element : list) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name,value);
        }
        //new c3p0连接池
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driveClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));

        configuration.setDataSource(comboPooledDataSource);

        //userMapper.xml解析：拿到路径--字节输入流--dom4j进行解析
        List<Element> mapperlist = rootElement.selectNodes("//mapper");
        for (Element element : mapperlist) {
            String resourcePath = element.attributeValue("resource");
            InputStream inputStream1 = Resources.getResourcesAsSteam(resourcePath);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            xmlMapperBuilder.paresConfig(inputStream1);
        }
        return configuration;
    }
}
